package com.ozner.cup.Device.Kettle;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ozner.Kettle.Kettle;
import com.ozner.cup.Base.BaseActivity;
import com.ozner.cup.Base.WebActivity;
import com.ozner.cup.Bean.Contacts;
import com.ozner.cup.Command.OznerPreference;
import com.ozner.cup.DBHelper.DBManager;
import com.ozner.cup.DBHelper.OznerDeviceSettings;
import com.ozner.cup.Device.Kettle.KettleRemindUtils.OznerRemindUtil;
import com.ozner.cup.Device.ReplenWater.RemindUtils.RemindUtil;
import com.ozner.cup.R;
import com.ozner.cup.Utils.LCLogUtils;
import com.ozner.device.OznerDeviceManager;
import com.zcw.togglebutton.ToggleButton;

import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.NumberPicker;
import cn.qqtheme.framework.picker.TimePicker;

public class SetUpKettleActivity extends BaseActivity {
    private static final String TAG = "SetUpKettleActivity";
    public static final String REMIND_START_MINUTE = "remind_start_minute";
    public static final String REMIND_END_MINUTE = "remind_end_minute";
    public static final String REMIND_INTERVAL = "remind_interval";
    public static final String REMIND_ENABLE = "remind_enable";
    private final long DEFAULT_INTERVAL = 24 * 3600 * 1000;//一天


    @InjectView(R.id.title)
    TextView title;
    @InjectView(R.id.toolbar)
    Toolbar toolbar;
    @InjectView(R.id.tv_device_name)
    TextView tvDeviceName;
    @InjectView(R.id.tb_tip_switch)
    ToggleButton tbTipSwitch;
    @InjectView(R.id.tv_tip_time_content)
    TextView tvTipTimeContent;
    @InjectView(R.id.tv_tip_time_start)
    TextView tvTipTimeStart;
    @InjectView(R.id.tv_tip_time_divide)
    TextView tvTipTimeDivide;
    @InjectView(R.id.tv_tip_time_end)
    TextView tvTipTimeEnd;
    @InjectView(R.id.tv_tip_interval_content)
    TextView tvTipIntervalContent;
    @InjectView(R.id.tv_tip_interval_value)
    TextView tvTipIntervalValue;
    @InjectView(R.id.tv_bolling_temp)
    TextView tvBollingTemp;
    @InjectView(R.id.llay_setup_bolling_temp)
    LinearLayout llaySetupBollingTemp;
    @InjectView(R.id.llay_about_kettle)
    LinearLayout llayAboutKettle;
    @InjectView(R.id.tv_delete_device)
    TextView tvDeleteDevice;

    private String mac;
    private Kettle mKettle;
    private String mUserid;
    private OznerDeviceSettings oznerSetting;
    private String deviceNewName = null;// deviceNewPos = null;
    private boolean isTipOn = false;
    private NumberPicker numberPicker;
    private Handler mHandler;
    private int bollingTemp = 100;
    private TimePicker timePickerStart, timePickerEnd;
    private boolean isStartTime = true;
    private Calendar startCalendar, endCalendar;
    private String[] intervalArray = new String[5];
    private int intervalValue = 30;
    private EditText et_newname;
    private RemindUtil remindUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_up_kettle);
        ButterKnife.inject(this);
        remindUtil = new RemindUtil(this);
        mHandler = new Handler();
        initToolBar();
        tbTipSwitch.setOnToggleChanged(new ToggleButton.OnToggleChanged() {
            @Override
            public void onToggle(boolean b) {
                isTipOn = b;
                enableTimeTip(b);
            }
        });
        initNumberPicker();
        initStartTimePicker();
        initEndTimePicker();
        initIntervalList();
        try {
            mUserid = OznerPreference.GetValue(this, OznerPreference.UserId, "");
            mac = getIntent().getStringExtra(Contacts.PARMS_MAC);
            Log.e(TAG, "onCreate: mac:" + mac);
            mKettle = (Kettle) OznerDeviceManager.Instance().getDevice(mac);
            oznerSetting = DBManager.getInstance(this).getDeviceSettings(mUserid, mac);
            if (oznerSetting != null) {
                LCLogUtils.E(TAG, "oznerSetting:" + oznerSetting.toString());
            }
            initViewData();
        } catch (Exception ex) {
            ex.printStackTrace();
            Log.e(TAG, "onCreate_Ex: " + ex.getMessage());
        }
    }

    /**
     * 初始化ToolBar
     */
    private void initToolBar() {
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        title.setText(R.string.kettle_mine);
        toolbar.setNavigationIcon(R.drawable.back);
    }

    private void initNumberPicker() {
        numberPicker = new NumberPicker(this);
        numberPicker.setAnimationStyle(R.style.AnimBottom);
        numberPicker.setDividerVisible(false);
        numberPicker.setDividerColor(ContextCompat.getColor(this, R.color.white));
        numberPicker.setTextColor(ContextCompat.getColor(this, R.color.black_deep));
        numberPicker.setRange(0, 100, 1);
        numberPicker.setOnNumberPickListener(new NumberPicker.OnNumberPickListener() {
            @Override
            public void onNumberPicked(int index, final Number item) {
                Log.e(TAG, "onNumberPicked: " + item.intValue());
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        tvBollingTemp.setText(String.format(Locale.getDefault(), "%d℃", item.intValue()));
                    }
                });
            }
        });
    }

    private void initStartTimePicker() {
        startCalendar = Calendar.getInstance();
        timePickerStart = new TimePicker(this, TimePicker.HOUR_24);
        timePickerStart.setLabel(getString(R.string.kettle_hour), getString(R.string.minutes));
        timePickerStart.setOnTimePickListener(new TimePicker.OnTimePickListener() {
            @Override
            public void onTimePicked(String hour, String minute) {
                startCalendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour));
                startCalendar.set(Calendar.MINUTE, Integer.parseInt(minute));
                tvTipTimeStart.setText(hour + ":" + minute);
            }
        });
    }

    private void initEndTimePicker() {
        endCalendar = Calendar.getInstance();
        timePickerEnd = new TimePicker(this, TimePicker.HOUR_24);
        timePickerEnd.setLabel(getString(R.string.kettle_hour), getString(R.string.minutes));
        timePickerEnd.setOnTimePickListener(new TimePicker.OnTimePickListener() {
            @Override
            public void onTimePicked(String hour, String minute) {
                endCalendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour));
                endCalendar.set(Calendar.MINUTE, Integer.parseInt(minute));
                tvTipTimeEnd.setText(hour + ":" + minute);
            }
        });
    }

    /**
     * 初始化提醒时间间隔数据
     */
    private void initIntervalList() {
        for (int i = 0; i < 4; i++) {
            intervalArray[i] = String.valueOf(i * 15 + 15);
        }
        intervalArray[4] = "120";
    }

    private void initViewData() {
        if (mKettle != null) {
            deviceNewName = mKettle.getName();
        }
        if (oznerSetting != null) {
            deviceNewName = oznerSetting.getName();
            Object remEnableObj = oznerSetting.getAppData(REMIND_ENABLE);
            isTipOn = remEnableObj != null ? Boolean.parseBoolean(String.valueOf(remEnableObj)) : false;
//            Object objStart = oznerSetting.getAppData(REMIND_START_MINUTE);
//            String strStartMin = formatTime(objStart != null ? Integer.parseInt(String.valueOf(objStart)) : 0);
//            Object objEnd = oznerSetting.getAppData(REMIND_END_MINUTE);
//            String strEndMin = formatTime(objEnd != null ? Integer.parseInt(String.valueOf(objEnd)) : 0);
            int[] starttime = getStartTime();
            int[] endtime = getEndTime();
            String strStartMin = formatTime(starttime[0], starttime[1]);
            String strEndMin = formatTime(endtime[0], endtime[1]);
            startCalendar.setTimeInMillis(Calendar.getInstance().getTimeInMillis());
            startCalendar.set(Calendar.HOUR_OF_DAY, starttime[0]);
            startCalendar.set(Calendar.MINUTE, starttime[1]);
            startCalendar.set(Calendar.MILLISECOND, 0);
            endCalendar.setTimeInMillis(Calendar.getInstance().getTimeInMillis());
            endCalendar.set(Calendar.HOUR_OF_DAY, endtime[0]);
            endCalendar.set(Calendar.MINUTE, endtime[1]);
            endCalendar.set(Calendar.MILLISECOND, 0);
            tvTipTimeStart.setText(strStartMin);
            tvTipTimeEnd.setText(strEndMin);
            Object objInterval = oznerSetting.getAppData(REMIND_INTERVAL);
            intervalValue = objInterval != null ? Integer.parseInt(String.valueOf(objInterval)) : 0;
            tvTipIntervalValue.setText(String.format(Locale.getDefault(), getString(R.string.interval_minutes), String.valueOf(intervalValue)));
            Log.e(TAG, "initViewData: isTipOn:" + isTipOn);

            if (isTipOn) {
                tbTipSwitch.setToggleOn();
            } else {
                tbTipSwitch.setToggleOff();
            }
            enableTimeTip(isTipOn);
        }
        tvDeviceName.setText(deviceNewName);
    }

    private int[] getStartTime() {
        Object objStart = oznerSetting.getAppData(REMIND_START_MINUTE);
        int start = objStart != null ? Integer.parseInt(String.valueOf(objStart)) : 0;
        return new int[]{start / 60, start % 60};
    }

    private int[] getEndTime() {
        Object objEnd = oznerSetting.getAppData(REMIND_END_MINUTE);
        int end = objEnd != null ? Integer.parseInt(String.valueOf(objEnd)) : 0;
        return new int[]{end / 60, end % 60};
    }

    private String formatTime(int hour, int min) {
        StringBuilder sbTime = new StringBuilder();
        if (hour < 10) {
            sbTime.append("0");
        }
        sbTime.append(hour);
        sbTime.append(":");
        if (min < 10) {
            sbTime.append("0");
        }
        sbTime.append(min);
        return sbTime.toString();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem item = menu.add(0, 0, 0, getString(R.string.save));

        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
//                new AlertDialog.Builder(SetUpKettleActivity.this).setTitle("").setMessage(getString(R.string.save_device))
//                        .setPositiveButton(getString(R.string.yes), new AlertDialog.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                SetUpKettleActivity.this.finish();
//                            }
//                        })
//                        .setNegativeButton(getString(R.string.no), new AlertDialog.OnClickListener() {
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                dialog.cancel();
//                                finish();
//                            }
//                        }).show();
//                break;
            case 0:
                if (TextUtils.isEmpty(deviceNewName)) {
                    showToastCenter(R.string.input_device_name);
                    return true;
                }
                if (isTipOn) {
                    if (startCalendar.getTimeInMillis() >= endCalendar.getTimeInMillis()) {
                        showToastCenter(R.string.time_end_befor_start);
                        return true;
                    }
                }

                new AlertDialog.Builder(SetUpKettleActivity.this).setTitle("").setMessage(getString(R.string.save_device))
                        .setPositiveButton(getString(R.string.yes), new AlertDialog.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                saveSettings();
                                finish();
                            }
                        })
                        .setNegativeButton(getString(R.string.no), new AlertDialog.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                finish();
                            }
                        }).show();
                break;
        }
        return true;
    }


    private void saveSettings() {
        if (mKettle != null) {
            mKettle.Setting().name(deviceNewName);
            int startMinute = startCalendar.get(Calendar.HOUR_OF_DAY) * 60 + startCalendar.get(Calendar.MINUTE);
            int endMinute = endCalendar.get(Calendar.HOUR_OF_DAY) * 60 + endCalendar.get(Calendar.MINUTE);

            if (oznerSetting == null) {
                oznerSetting = new OznerDeviceSettings();
                oznerSetting.setUserId(mUserid);
                oznerSetting.setCreateTime(String.valueOf(new Date().getTime()));
                oznerSetting.setDevcieType(mKettle.Type());
            }
            oznerSetting.setName(deviceNewName);
            oznerSetting.setStatus(0);
            oznerSetting.setMac(mKettle.Address());
            oznerSetting.setDevicePosition(getString(R.string.kettle_mine));

            if (isTipOn) {
                oznerSetting.setAppData(REMIND_START_MINUTE, startMinute);
                oznerSetting.setAppData(REMIND_END_MINUTE, endMinute);
                oznerSetting.setAppData(REMIND_INTERVAL, intervalValue);
                OznerRemindUtil.getInstance(getApplicationContext()).stopRemind(OznerRemindUtil.REQ_CODE_KETTLE);
                OznerRemindUtil.getInstance(getApplicationContext())
                        .startRemind(OznerRemindUtil.REQ_CODE_KETTLE, startCalendar, endCalendar, intervalValue * 60000);
            } else {
                OznerRemindUtil.getInstance(getApplicationContext()).stopRemind(OznerRemindUtil.REQ_CODE_KETTLE);
            }
            oznerSetting.setAppData(REMIND_ENABLE, isTipOn);
            mKettle.updateSettings();
            DBManager.getInstance(this).updateDeviceSettings(oznerSetting);
            OznerDeviceManager.Instance().save(mKettle);


        } else {
            showToastCenter(R.string.Not_found_device);
        }
    }


    /**
     * 显示设置名字对话框
     */
    private void showSetNameDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(SetUpKettleActivity.this, AlertDialog.THEME_HOLO_LIGHT);

        final View inputView = LayoutInflater.from(SetUpKettleActivity.this).inflate(R.layout.add_pos_view, null);
        builder.setTitle(R.string.set_device_name);
        builder.setView(inputView);
        et_newname = (EditText) inputView.findViewById(R.id.et_addPos);
        et_newname.setHint(R.string.input_kettle_name);

        builder.setPositiveButton(R.string.ensure, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(final DialogInterface dialog, int which) {
                if (et_newname.getText().toString().trim().length() > 0) {
                    deviceNewName = et_newname.getText().toString().trim();
//                    deviceNewPos = "";
                    tvDeviceName.setText(et_newname.getText().toString().trim());
                }
                dialog.cancel();
            }
        });
        builder.setNegativeButton(R.string.cancle, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.create().show();
    }

    /**
     * 显示饮水提醒间隔对话框
     */
    private void showIntervalDialog() {
        String selInterval = String.valueOf(intervalValue);
        int checkIndex = -1;
        for (int i = 0; i < intervalArray.length; i++) {
            if (selInterval.equals(intervalArray[i])) {
                checkIndex = i;
                break;
            }
        }
        new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT)
                .setTitle(R.string.set_remind_interval)
                .setSingleChoiceItems(intervalArray, checkIndex, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, final int which) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                intervalValue = Integer.parseInt(intervalArray[which]);
                                tvTipIntervalValue.setText(String.format(Locale.getDefault(), getString(R.string.interval_minutes), intervalArray[which]));
                            }
                        });
                        dialog.cancel();
                    }
                }).show();
    }


    /**
     * 切换饮水提醒时间状态
     *
     * @param enable
     */
    private void enableTimeTip(boolean enable) {
        tvTipTimeContent.setEnabled(enable);
        tvTipTimeStart.setEnabled(enable);
        tvTipTimeDivide.setEnabled(enable);
        tvTipTimeEnd.setEnabled(enable);
        tvTipIntervalContent.setEnabled(enable);
        tvTipIntervalValue.setEnabled(enable);
        tvTipTimeStart.setClickable(enable);
        tvTipTimeEnd.setClickable(enable);
        tvTipIntervalValue.setClickable(enable);
    }

    @OnClick({R.id.tv_delete_device, R.id.llay_device_name, R.id.tv_tip_time_start, R.id.tv_tip_time_end, R.id.tv_tip_interval_value, R.id.llay_setup_bolling_temp, R.id.llay_about_kettle})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_delete_device:
                new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_LIGHT).setMessage(R.string.delete_this_device)
                        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (mKettle != null) {
                                    DBManager.getInstance(SetUpKettleActivity.this).deleteDeviceSettings(mUserid, mKettle.Address());
                                    OznerDeviceManager.Instance().remove(mKettle);
                                    setResult(RESULT_OK);
                                    SetUpKettleActivity.this.finish();
                                }
                            }
                        }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).show();
                break;
            case R.id.llay_device_name:
                showSetNameDialog();
                break;
            case R.id.tv_tip_time_start:
                isStartTime = true;
                int[] starttime = getStartTime();
                Log.e(TAG, "onViewClicked: StartTime:" + starttime[0] + ":" + starttime[1]);
//                timePicker.dismiss();
                timePickerStart.setSelectedItem(starttime[0], starttime[1]);
                timePickerStart.show();
                break;
            case R.id.tv_tip_time_end:
                isStartTime = false;
                int[] endtime = getEndTime();
//                Log.e(TAG, "onViewClicked: EndTime:"+endtime[0]+":"+endtime[1]);
//                timePicker.dismiss();
                timePickerEnd.setSelectedItem(endtime[0], endtime[1]);
                timePickerEnd.show();
                break;
            case R.id.tv_tip_interval_value:
                showIntervalDialog();
                break;
            case R.id.llay_setup_bolling_temp:
                numberPicker.setSelectedItem(bollingTemp);
                if (numberPicker.isShowing()) {
                    numberPicker.dismiss();
                } else {
                    numberPicker.show();
                }
                break;
            case R.id.llay_about_kettle:
                Intent webIntent = new Intent(this, WebActivity.class);
                webIntent.putExtra(Contacts.PARMS_URL, "www.baidu.com");
                startActivity(webIntent);
                break;
        }
    }
}
